import type { FC } from 'react'
import React from 'react'
import { createRoot } from 'react-dom/client'
import { withNativeProps } from '../../../src/utils/native-props'
import { type ComponentProps } from '../../global/common-style'

const classPrefix = `gd-toast`

export type ToastProps = {
  message?: string
  icon?: string
} & ComponentProps

export const ToastComponent: FC<ToastProps> = (props) => {
  const { message, icon } = props

  return withNativeProps(
    props,
    <div className={`${classPrefix}`}>
      <div className={`${classPrefix}-contain`}>
        {icon && <img src={icon} className={`${classPrefix}-icon`} />}
        <div className={`${classPrefix}-text`}>{message}</div>
      </div>
    </div>
  )
}

const destroyToast = (node: any) => {
  const pageElement = document.getElementById('root')
  const div = document.createElement('div')
  const root = createRoot(div)
  root.unmount()
  pageElement?.removeChild(node)
}

export const Toast = (props: ToastProps) => {
  const div = document.createElement('div')
  /**
   * 根元素是id="root"，在根元素下添加div节点并定时销毁
   * Taro框架下会自动生成一个id=当前页面path的节点，所以在Taro框架下需要根据Taro.getCurrentPages().$taroPath获取到id
   */
  const pageElement = document.getElementById('root')

  const root = createRoot(div)
  root.render(<ToastComponent message={props.message} icon={props.icon} />)
  pageElement?.appendChild(div)
  setTimeout(() => {
    destroyToast(div)
  }, 1500)
  return () => {
    destroyToast(div)
  }
}
